import type { IUserInfoResp } from '../me'
import { readonly, ref } from 'vue'
import { getUserInfoApi } from '@/api'

// 用户信息状态
const userInfo = ref<IUserInfoResp | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)

// 获取用户信息
async function fetchUserInfo() {
  loading.value = true
  error.value = null

  try {
    // 调用API获取用户信息
    const resp = await getUserInfoApi()
    userInfo.value = resp
  }
  catch (err) {
    error.value = err instanceof Error ? err.message : '获取用户信息失败'
  }
  finally {
    loading.value = false
  }
}

// 刷新用户信息
async function refreshUserInfo() {
  await fetchUserInfo()
}

// 清空用户信息
function clearUserInfo() {
  userInfo.value = null
  error.value = null
}

export function useUserInfo() {
  return {
    userInfo: readonly(userInfo),
    loading: readonly(loading),
    error: readonly(error),
    fetchUserInfo,
    refreshUserInfo,
    clearUserInfo,
  }
}
